package com.web.controller.crawler;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang.SerializationUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
import com.web.model.crawler.TbGrading;
import com.web.rabbitmq.crawler.Rabbit;
import com.web.thread.crawler.PcComThread;
import com.web.util.crawler.Json;

/**
 * 通过Pc网页端淘宝首页进行分析抓取
 * 
 * @author G8670
 * 
 */
@RestController
@RequestMapping("/PcCommodityAction")
public class PcCommodityAction {

	private String QUEUE_NAME = "grading";// 三级分类队列频道标识

	private static final Logger logger = Logger.getLogger(PcCommodityAction.class);

	/**
	 * 对分类进行产品列表查询
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/add")
	public Json add() {
		Json jsondata = new Json();// Action返回json数据
		// 创建一个可重用固定线程数的线程池
		ExecutorService pool = Executors.newFixedThreadPool(5);

		Connection connection = Rabbit.getConnection();// 获取队列连接
		Channel channel = Rabbit.getChannel(connection, QUEUE_NAME);// 获取队列频道
		// 定义队列的消费者
		QueueingConsumer consumer = new QueueingConsumer(channel);
		// 监听队列
		try {
			channel.basicConsume(QUEUE_NAME, false, consumer);
		} catch (IOException e) {
			logger.info("监听队列失败");
		}

		while (true) {
			// 获取队列中的消息
			QueueingConsumer.Delivery delivery = null;
			try {
				delivery = consumer.nextDelivery();
			} catch (Exception e) {
				logger.info("获取队列消息失败");
			}
			TbGrading grading = (TbGrading) SerializationUtils.deserialize(delivery.getBody());
			if (("-1").equals(grading.getId())) {
				break;
			} else if (("三级菜单").equals(grading.getGrade())) {
				PcComThread pcComThread = new PcComThread(grading);
				// 将线程放入池中进行执行
				pool.execute(pcComThread);
				// System.out.println(delivery + "接受到的消息 '" + grading.getName().toString() + "'");
			}

		}

		jsondata.setSuccess(true);
		return jsondata;
	}

}
